'''
Created on Jul 9, 2011

@author: kafkef
'''

import sys
import traceback

from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt

from dexen.system.client import ui
from dexen.system.common import service


svr_proxy = ui.svr_proxy


class ConnectionWidget(QWidget):
    def __init__(self):
        super(ConnectionWidget, self).__init__()
        self.curSvrAddr = ""
        self._setupWidgets()

    def _setupWidgets(self):
        # Create widgets
        self.label = QLabel("Server Address:")
        self.lineEdit = QLineEdit(service.get_my_ip())
        self.connectBtn = QPushButton("Connect")
        self.connectBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        
        # Setup layout
        hLayout = QHBoxLayout()
        hLayout.addWidget(self.label)
        hLayout.addWidget(self.lineEdit)
        hLayout.addWidget(self.connectBtn)
        self.setLayout(hLayout)
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        
        # Configure signal/slots
        self.connect(self.connectBtn, SIGNAL("clicked()"), self.on_connectBtn_clicked)
            
    def _connect(self):
        try:
            self.setCursor(QCursor(Qt.WaitCursor))
            self.curSvrAddr = str(self.lineEdit.text())
            svr_proxy.connect(self.curSvrAddr)
            start_time = svr_proxy.get_start_time()
        except:
            traceback.print_tb(sys.exc_info()[2])
            print "Connection is failed"
            msgBox = QMessageBox(self)
            msgBox.setWindowTitle("Connection failure")
            msg = "Cannot access the dexen server.\n"
            msg += "Make sure the address is valid and the server is running." 
            msgBox.setText(msg)
            msgBox.exec_()
        else:
            self.emit(SIGNAL("connected"), self.curSvrAddr, start_time)
            self.connectBtn.setText("Disconnect")
            self.lineEdit.setEnabled(False)
        finally:
            self.setCursor(QCursor(Qt.ArrowCursor))    
    
    def _disconnect(self):
        svr_proxy.disconnect()
        self.connectBtn.setText("Connect")
        self.lineEdit.setEnabled(True)
        self.emit(SIGNAL("disconnected()"))
    
    def on_connectBtn_clicked(self):
        if self.connectBtn.text() == "Connect":
            self._connect()
        else:
            self._disconnect()
            
